package com.rinlink.jbcodec.creator;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rinlink.jbcodec.common.CreatorUtils;
import com.rinlink.jbcodec.exception.FieldValueException;
import com.rinlink.jbcodec.transform.Transform;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;


public abstract class ArrayToBytesCreator<T> extends ObjectToBytesCreator<JSONArray> {

    private Class<T> itemJavaClass;
    public ArrayToBytesCreator(){
        super(JSONArray.class);
        Type type = getClass().getGenericSuperclass();
        ParameterizedType ptype=(ParameterizedType)type;
        Type[] types = ptype.getActualTypeArguments();
        this.itemJavaClass = (Class<T>) types[0];
    }

    public ArrayToBytesCreator(Class t){
        super(JSONArray.class);
        this.itemJavaClass = t;
    }



    @Override
    protected Transform<byte[]> create(JSONArray objects, JSONObject attr, JSONObject source) {
        int arraySize = CreatorUtils.getArraySize(attr);
        if (objects.size() != arraySize)
            throw new FieldValueException();
        List<T> list = objects.toJavaList(itemJavaClass);
        return create(list,attr, source);
    }


    protected abstract Transform<byte[]> create(List<T> ts, JSONObject attr, JSONObject source);

}